using System;
using System.Collections.ObjectModel;
using System.Windows;
using CleanUpTool.Models;

namespace CleanUpTool.Views
{
    public partial class ConfigurationWindow : Window
    {
        private readonly CleanupConfiguration _configuration;
        private readonly ObservableCollection<DirectoryConfig> _directories;

        public ConfigurationWindow(CleanupConfiguration configuration)
        {
            InitializeComponent();
            _configuration = configuration;
            _directories = new ObservableCollection<DirectoryConfig>(_configuration.SavedDirectories);
            lvDirectories.ItemsSource = _directories;

            // 绑定设置
            chkAutoScan.IsChecked = _configuration.AutoScanAfterSelect;
            chkShowConfirmation.IsChecked = _configuration.ShowConfirmationBeforeCleanup;
        }

        private void btnAddDirectory_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new System.Windows.Forms.FolderBrowserDialog
            {
                Description = "选择要添加的目录",
                UseDescriptionForTitle = true
            };

            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string path = dialog.SelectedPath;
                string name = System.IO.Path.GetFileName(path);

                if (!_directories.Any(d => d.Path.Equals(path, StringComparison.OrdinalIgnoreCase)))
                {
                    _directories.Add(new DirectoryConfig
                    {
                        Name = name,
                        Path = path,
                        IsEnabled = true,
                        LastCleanupTime = DateTime.Now
                    });
                }
                else
                {
                    System.Windows.MessageBox.Show("该目录已存在", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                }
            }
        }

        private void btnRemoveDirectory_Click(object sender, RoutedEventArgs e)
        {
            var selectedItem = lvDirectories.SelectedItem as DirectoryConfig;
            if (selectedItem != null)
            {
                _directories.Remove(selectedItem);
            }
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            // 更新配置
            _configuration.SavedDirectories.Clear();
            _configuration.SavedDirectories.AddRange(_directories);
            _configuration.AutoScanAfterSelect = chkAutoScan.IsChecked ?? true;
            _configuration.ShowConfirmationBeforeCleanup = chkShowConfirmation.IsChecked ?? true;

            // 保存配置
            _configuration.Save();

            DialogResult = true;
            Close();
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }
    }
}